<?php

namespace App\Http\Controllers\Shop;

use App\Model\AddMerchant;
use App\Model\AdminLogsModel;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;


class MerchantController extends Controller
{
	//商铺列表
	public function index(){
		$keyword = request()->keywords;
		$list = AddMerchant::where(function($query){
			if(request()->keywords){
				$query->where('shop','like',"%".request()->keywords."%");
				$query->Orwhere('location', 'like',"%".request()->keywords."%");
				$query->Orwhere('phone', 'like',"%".request()->keywords."%");
			}

		})->orderBy('id','desc')->paginate(15);

		return view('shop.merchant.index',compact('list','keyword'));
	}

	//添加
	public function add(){
		return view('shop.merchant.add');
	}

	//添加
	public function insert(){
		if(AddMerchant::where('shop',request()->name)->first()){
			return ['code'=>0,'msg'=>'该店铺已存在'];
		}
		DB::beginTransaction();
		try{
			$list = AddMerchant::create([
				'shop' => request()->name,
				'phone' => request()->phone,
				'location' =>request()->location,
				'remark' => request()->remark,
			]);
			$msg = '【货源后台】添加商家:'.request()->name.'(id:'.$list['id'].')';
			AdminLogsModel::addLogs($msg);
			DB::commit();
			return ['code'=>1,'msg'=>'添加成功'];
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>'添加失败'];
		}
	}

	//编辑
	public function edit(){
		$id = request()->id;
		$list = AddMerchant::where('id',$id)->first();
		return view('shop.merchant.edit',compact('list','id'));
	}
	//编辑
	public function update(){
		if(!request()->id){
			return ['code'=>0,'msg'=>'非法入侵'];
		}

		DB::beginTransaction();
		try{
			$list = AddMerchant::where('id',request()->id)->first();
			AddMerchant::where('id',request()->id)->update([
				'shop' => request()->shop,
				'phone' => request()->phone,
				'location' => request()->location,
				'remark' => request()->remark,
			]);
			$msg = '【货源后台】编辑商家信息:'.$list['shop'].'(id:'.request()->id.')';
			AdminLogsModel::addLogs($msg);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>'更改失败'];
		}
		return ['code'=>1,'msg'=>'更改成功'];
	}

	//删除
	public function del(){
		Db::beginTransaction();
		try{
			$list = AddMerchant::where('id',request()->id)->first();
			AddMerchant::where('id',request()->id)->delete();
			$msg = '【货源后台】删除商家'.$list['shop'].'(id:'.request()->id.')';
			AdminLogsModel::addLogs($msg);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}
		return ['code'=>1,'msg'=>'删除成功'];
	}
}